/*
 * #%L
 * Server
 * %%
 * Copyright (C) 2011 Ractoc.com
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
package com.ractoc.opengamefinder.server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.PropertyConfigurator;

import com.ractoc.pffj.core.PluginController;
import com.ractoc.tools.logging.ConfigureJulFromLog4j;
import java.io.File;
import org.apache.log4j.Logger;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 * Startup class for the server. <p/> <p/> <p/> <p/> <p/> <p/>
 * <p/>
 * @author ractoc
 * @version 0.1
 */
public final class OGFServerStartup {

    private static Logger logger = Logger.getLogger(OGFServerStartup.class.getName());

    /**
     * Default constructor.
     */
    private OGFServerStartup() {
    }

    /**
     * Main startup method.
     * @param args Argument supplied to the server at startup. Currently, no arguments are expected or parsed.
     */
    //CHECKSTYLE:OFF
    public static void main(final String[] args) {
        //CHECKSTYLE:ON
        Runtime.getRuntime().addShutdownHook(new ShutDownServer());
        String log4jConfigFile = ConfigLocator.getCustomConfig("log4j.xml");
        if (log4jConfigFile != null) {
            PropertyConfigurator.configureAndWatch(log4jConfigFile);
        } else {
            PropertyConfigurator.configureAndWatch("log4j.xml");
        }

        ConfigureJulFromLog4j cjfl4j = new ConfigureJulFromLog4j();
        try {
            cjfl4j.configure();
        } catch (FileNotFoundException ex) {
            logger.error("unable to configure JUL form Log4J. JUL messages will not be logged.", ex);
        } catch (IOException ex) {
            logger.error("unable to configure JUL form Log4J. JUL messages will not be logged.", ex);
        }

        if (args.length
                == 1) {
            logger.debug("startup argument: " + args[0]);
            String customConfig = ConfigLocator.getCustomConfig("hibernate.cfg.xml");
            Configuration config = null;
            if (customConfig != null) {
                config = new AnnotationConfiguration().configure(new File(customConfig));
            } else {
                config = new AnnotationConfiguration().configure("hibernate.cfg.xml");
            }
            if (("install").equalsIgnoreCase(args[0])) {
                new SchemaExport(config).drop(true, true);
                new SchemaExport(config).create(true, true);
                logger.info("Database installed succesfully");
            } else if (("update").equalsIgnoreCase(args[0])) {
                new SchemaUpdate(config).execute(false, true);
                logger.info("Database updated succesfully");
            } else {
                throw new RuntimeException("Unknown parameter: " + args[0]);
            }
            System.exit(0);
        }
        // Instantiate and startup the plugin controller
        final ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
        String pffjConfigFile = ConfigLocator.getCustomConfig("PFfJServer.xml");

        if (pffjConfigFile
                == null) {
            pffjConfigFile = "/configuration/pffj/PFfJServer.xml";
        }

        threadExecutor.submit(
                (Callable<Integer>) new PluginController(
                pffjConfigFile));
    }
}
